package com.phaeton.beemeup;

import org.andengine.entity.Entity;
import org.andengine.entity.scene.Scene;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import android.util.Log;

import com.phaeton.beemeup.constants.SceneConstants;
import com.phaeton.beemeup.entity.Cell;
import com.phaeton.beemeup.util.Coordinate;

public class Level extends Scene{
	private Cell[][] cells;
	private ITextureRegion tex;
	private VertexBufferObjectManager vbo;
	private int cols;
	private int rows;
	
	public Level(ITextureRegion tex, VertexBufferObjectManager vbo) {
		super();
		this.tex = tex;
		this.vbo = vbo;
		
		for(int i = 0; i < SceneConstants.LAYER_COUNT; i++) {
			this.attachChild(new Entity());
		}

        this.setTouchAreaBindingOnActionDownEnabled(true);
        this.setTouchAreaBindingOnActionMoveEnabled(false);
        this.setOnAreaTouchTraversalFrontToBack();
	}
	
	public void setDimension(int cols, int rows){
		this.cols = cols;
		this.rows = rows;
		cells = new Cell[cols][rows];
	}
	
	public Coordinate getDimension(){
		return new Coordinate(cols, rows);
	}
	
	public void buildLevel(){
		float side = (float)Math.sin(Math.PI/6)*tex.getHeight();
		float pad = (float)Math.sin(Math.PI/6)*tex.getWidth()/2;
		
		for(int i = 0; i < rows; i++) {
			for(int j = 0; j < cols; j+=2) {
				Cell cell = new Cell(j, i, j*(tex.getWidth()+side)/2, i*tex.getHeight(), tex, vbo) {
					@Override
					public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
						if(pSceneTouchEvent.isActionDown()) {
							Log.e("Bee", "id "+this.getCoordinates());
							return true;
						}
						return false;						
					}
				};
				cells[j][i] = cell;
				
				if(j < cols - 1){
					Cell cell2 = new Cell(j+1, i, (j+1)*(tex.getWidth()+side)/2, (i+.5f)*tex.getHeight(), tex, vbo) {
						@Override
						public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
							if(pSceneTouchEvent.isActionDown()) {
								Log.e("Bee", "id "+this.getCoordinates());
								return true;
							}
							return false;						
						}
					};
					cells[j+1][i] = cell2;
				}
			}
		}
	}
	
	public Cell getCell(int col, int row) {
		return cells[col][row];
	}
	
	public Cell[][] getCells(){
		return cells;
	}
}
